<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
    :disabled="disabled"
  >
    <el-table :data="formData" show-summary :summary-method="getSummaries" class="-mt-10px">
      <el-table-column label="序号" type="index" align="center" width="60" />
  <el-table-column min-width="180" label="产品编号" align="center" prop="no" />
  <el-table-column min-width="180" label="产品名称" align="center" prop="no" />
  <el-table-column min-width="180" label="产品图" align="center" prop="no" />
  <el-table-column min-width="180" label="产品分类" align="center" prop="no" />
  <el-table-column min-width="180" label="产品属性" align="center" prop="no" />
  <el-table-column min-width="180" label="产品规格" align="center" prop="no" />
  <el-table-column min-width="180" label="可用库存" align="center" prop="no" />
  <el-table-column min-width="180" label="基本单价" align="center" prop="no" />
  <el-table-column min-width="180" label="需求数量" align="center" prop="no" />
  <el-table-column min-width="180" label="应入数量" align="center" prop="no" />
  <el-table-column min-width="180" label="工单完成数" align="center" prop="no" />
  <el-table-column min-width="180" label="检验状态" align="center" prop="no" />
  <el-table-column min-width="180" label="合格数量" align="center" prop="no" />
  <el-table-column min-width="180" label="报废数量" align="center" prop="no" />
  <el-table-column min-width="180" label="返工数量" align="center" prop="no" />
  <el-table-column min-width="180" label="入库仓库 " align="center" prop="no" />
  <el-table-column min-width="180" label="副单位" align="center" prop="no" />
  <el-table-column min-width="180" label="货号" align="center" prop="no" />
  <el-table-column min-width="180" label="规格" align="center" prop="no" />
  <el-table-column min-width="180" label="累计入库数量" align="center" prop="no" />
  <el-table-column min-width="180" label="外箱尺寸" align="center" prop="no" />
  <el-table-column min-width="180" label="基本数量" align="center" prop="no" />
  <el-table-column min-width="180" label="客户名称" align="center" prop="no" />
  <el-table-column min-width="180" label="金额" align="center" prop="no" />
  <el-table-column min-width="180" label="包装" align="center" prop="no" />
  <el-table-column min-width="180" label="基本单位" align="center" prop="no" />
  <el-table-column min-width="180" label="辅助单位" align="center" prop="no" />
  <el-table-column min-width="180" label="辅助数量" align="center" prop="no" />
  <el-table-column min-width="180" label="辅助单价" align="center" prop="no" />
  <el-table-column min-width="180" label="备注" align="center" prop="no" />
  <el-table-column min-width="180" label="销售提成" align="center" prop="no" />
  <el-table-column min-width="180" label="切割费用/米" align="center" prop="no" />
  <el-table-column min-width="180" label="单位材料成本" align="center" prop="no" />
  <el-table-column min-width="180" label="刺穿点费用/个" align="center" prop="no" />
  <el-table-column min-width="180" label="材料成本" align="center" prop="no" />
  <el-table-column min-width="180" label="打点费用/个" align="center" prop="no" />
  <el-table-column min-width="180" label="单位人工成本" align="center" prop="no" />
  <el-table-column min-width="180" label="折弯单价" align="center" prop="no" />
  <el-table-column min-width="180" label="人工成本" align="center" prop="no" />
  <el-table-column min-width="180" label="备注" align="center" prop="no" />
  <el-table-column min-width="180" label="基本单位成本" align="center" prop="no" />
  <el-table-column min-width="180" label="辅助单位成本" align="center" prop="no" />
  <el-table-column min-width="180" label="入库成本" align="center" prop="no" />
  <el-table-column min-width="180" label="客户编号" align="center" prop="no" />
  <el-table-column min-width="180" label="颜色" align="center" prop="no" />
  <el-table-column min-width="180" label="尺码" align="center" prop="no" />
  <el-table-column min-width="180" label="q21222" align="center" prop="no" />
  <el-table-column min-width="180" label="1111" align="center" prop="no" />
  <el-table-column min-width="180" label="单重" align="center" prop="no" />
  <el-table-column min-width="180" label="长" align="center" prop="no" />
  <el-table-column min-width="180" label="宽" align="center" prop="no" />
  <el-table-column min-width="180" label="高" align="center" prop="no" />
  <el-table-column min-width="180" label="密度" align="center" prop="no" />
  <el-table-column min-width="180" label="单重66" align="center" prop="no" />
   <el-table-column min-width="180" label="头标" align="center" prop="no" />
   <el-table-column min-width="180" label="合同编号" align="center" prop="no" />
   <el-table-column min-width="180" label="淘宝货号" align="center" prop="no" />
   <el-table-column min-width="180" label="压纹" align="center" prop="no" />
   <el-table-column min-width="180" label="工艺" align="center" prop="no" />
  <el-table-column min-width="180" label="颜色" align="center" prop="no" />
  <el-table-column min-width="180" label="OE码1" align="center" prop="no" />
  <el-table-column min-width="180" label="OE码2" align="center" prop="no" />
  <el-table-column min-width="180" label="OE码3" align="center" prop="no" />   <el-table-column min-width="180" label="胶辊" align="center" prop="no" />
  <el-table-column min-width="180" label="客户产品编码" align="center" prop="no" />
  <el-table-column min-width="180" label="二级价格" align="center" prop="no" />
  <!--  
	<el-table-column label="仓库名称" min-width="125">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.warehouseId`"
            :rules="formRules.warehouseId"
            class="mb-0px!"
          >
            <el-select
              v-model="row.warehouseId"
              clearable
              filterable
              placeholder="请选择仓库"
              @change="onChangeWarehouse($event, row)"
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品名称" min-width="180">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productId`" :rules="formRules.productId" class="mb-0px!">
            <el-select
              v-model="row.productId"
              clearable
              filterable
              @change="onChangeProduct($event, row)"
              placeholder="请选择产品"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="库存" min-width="100">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.stockCount" :formatter="erpCountInputFormatter" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="条码" min-width="150">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.productBarCode" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位" min-width="80">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.productUnitName" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="数量" prop="count" fixed="right" min-width="140">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.count`" :rules="formRules.count" class="mb-0px!">
            <el-input-number
              v-model="row.count"
              controls-position="right"
              :min="0.001"
              :precision="3"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品单价" fixed="right" min-width="120">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productPrice`" class="mb-0px!">
            <el-input-number
              v-model="row.productPrice"
              controls-position="right"
              :min="0.01"
              :precision="2"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="合计金额" prop="totalPrice" fixed="right" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.totalPrice`" class="mb-0px!">
            <el-input disabled v-model="row.totalPrice" :formatter="erpPriceInputFormatter" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`" class="mb-0px!">
            <el-input v-model="row.remark" placeholder="请输入备注" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column> -->
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3" v-if="!disabled">
    <el-button @click="handleAdd" round>+ 添加入库产品</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/warehouse'
import { StockApi } from '@/api/erp/stock/stock'
import {
  erpCountInputFormatter,
  erpPriceInputFormatter,
  erpPriceMultiply,
  getSumValue
} from '@/utils'

const props = defineProps<{
  items: undefined
  disabled: false
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  inId: [{ required: true, message: '入库编号不能为空', trigger: 'blur' }],
  warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '产品不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '产品数量不能为空', trigger: 'blur' }]
})
const formRef = ref([]) // 表单 Ref
const productList = ref<ProductVO[]>([]) // 产品列表
const warehouseList = ref<WarehouseVO[]>([]) // 仓库列表
const defaultWarehouse = ref<WarehouseVO>(undefined) // 默认仓库

/** 初始化设置入库项 */
watch(
  () => props.items,
  async (val) => {
    formData.value = val
  },
  { immediate: true }
)

/** 监听合同产品变化，计算合同产品总价 */
watch(
  () => formData.value,
  (val) => {
    if (!val || val.length === 0) {
      return
    }
    // 循环处理
    val.forEach((item) => {
      item.totalPrice = erpPriceMultiply(item.productPrice, item.count)
    })
  },
  { deep: true }
)

/** 合计 */
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (['count', 'totalPrice'].includes(column.property)) {
      const sum = getSumValue(data.map((item) => Number(item[column.property])))
      sums[index] =
        column.property === 'count' ? erpCountInputFormatter(sum) : erpPriceInputFormatter(sum)
    } else {
      sums[index] = ''
    }
  })

  return sums
}

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    warehouseId: defaultWarehouse.value?.id,
    productId: undefined,
    productUnitName: undefined, // 产品单位
    productBarCode: undefined, // 产品条码
    productPrice: undefined,
    stockCount: undefined,
    count: 1,
    totalPrice: undefined,
    remark: undefined
  }
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 处理仓库变更 */
const onChangeWarehouse = (warehouseId, row) => {
  // 加载库存
  setStockCount(row)
}

/** 处理产品变更 */
const onChangeProduct = (productId, row) => {
  const product = productList.value.find((item) => item.id === productId)
  if (product) {
    row.productUnitName = product.unitName
    row.productBarCode = product.barCode
    row.productPrice = product.minPrice
  }
  // 加载库存
  setStockCount(row)
}

/** 加载库存 */
const setStockCount = async (row) => {
  if (!row.productId || !row.warehouseId) {
    return
  }
  const stock = await StockApi.getStock2(row.productId, row.warehouseId)
  row.stockCount = stock ? stock.count : 0
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}
defineExpose({ validate })

/** 初始化 */
onMounted(async () => {
  productList.value = await ProductApi.getProductSimpleList()
  warehouseList.value = await WarehouseApi.getWarehouseSimpleList()
  defaultWarehouse.value = warehouseList.value.find((item) => item.defaultStatus)
  // 默认添加一个
  if (formData.value.length === 0) {
    handleAdd()
  }
})
</script>
